package com.hsq.reflection.Class_;

import com.hsq.reflection.Car;

import java.lang.reflect.Field;

//Class类的常用方法
public class Class02 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        String classAllPath = "com.hsq.reflection.Car";
        //<?>表示不确定的Java类型
        Class<?> cls = Class.forName(classAllPath);
        System.out.println(cls);//显示cls对象，是哪个类的Class对象 com.hsq.reflection.Car
        System.out.println(cls.getClass()); //cls的运行类型java.lang.Class
        //得到包名com.hsq.reflection
        System.out.println(cls.getPackage().getName());
        //得到全名com.hsq.reflection.Car
        System.out.println(cls.getName());
        //通过cls创建实例
        Car car = (Car)cls.newInstance();
        System.out.println(car);
        //通过反射得到属性
        Field name = cls.getField("name");
        System.out.println(name.get(car));
        //通过反射给属性赋值
        name.set(car, "xiaomi");
        System.out.println(name.get(car));
        //得到所有属性
        System.out.println("======All======");
        Field[] fields = cls.getFields();
        for(Field f: fields) {
            System.out.println(f.getName());
            System.out.println(f.get(car));
        }
    }
}
